package com.bxait;

import com.bxait.utils.ESClientSingle;
import com.bxait.utils.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;

/**
 * @author Chen
 * @description: es更新数据
 * @ClassName ESTest_Client
 * @create 2023-04-08 16:16
 * @Version 1.0
 */
public class ESTest_Doc_Update {

    public static void main(String[] args) throws IOException {
        // 创建ES的客户端
        RestHighLevelClient client = ESClientSingle.getInstant();

        // 根据id进行更新
        updateById(client);
        // 全量更新
//        update(client);
        // 关闭es客户端
        client.close();
    }

    private static void updateById(RestHighLevelClient client) throws IOException {
        // 修改数据
        UpdateRequest request = new UpdateRequest();
        request.index("user").id("1001");
        request.doc(XContentType.JSON,"sex","女");
        client.update(request,RequestOptions.DEFAULT);
    }

    private static void update(RestHighLevelClient client) throws IOException {
        UpdateRequest request = new UpdateRequest();
        request.index("user").id("1001");
        // 需要插入的数据
        User user = new User("zhangSan","不男不女",18);
        // 将数据转化为JSON
        ObjectMapper mapper = new ObjectMapper();
        String userJson = mapper.writeValueAsString(user);
        request.doc(userJson,XContentType.JSON);
        client.update(request,RequestOptions.DEFAULT);
    }

}
